﻿/// <reference path="../../../../sustainalytics.companies.ui/modules/companysearchmodule/controller/companysearchcontroller.ts" />
/// <reference path="../../../../sustainalytics.companies.ui/modules/companysearchmodule/controller/companysearchcontroller.ts" />
/// <reference path="../../../../Sustainalytics.News.Admin.UI/modules/Notifications.Admin/models/NotificationDto.ts" />
module Sustainalytics.Home {

    import Common = Sustainalytics.Common;
    import Portfolio = Sustainalytics.Portfolio;
    import NotificationDto = Sustainalytics.Notifications.Admin.NotificationDto;

    // Home controller
    export class HomeController {
        
        public newsTopList: NewsDashboardDto[];
        public eventsTopList: EventDashboardDto[];
        public insightsTopList: InsightDashboardDto[];
        public portfoliosTopList: PortfolioDashboardDto[];
        public mostActiveReportsTopList: MostActiveReports.MostActiveReportDto[];
        public mostRecentActivityTopList: MostRecentActivity.MostRecentActivityDto[];

        private accountId: string;
        private userId: string;
        
        //news order by column
        public newsOrderByCol: string;
        //news order by direction
        public newsOrderByColAsc: boolean;
        // order by column
        public eventOrderByCol: string;
        // order by direction
        public eventOrderByColAsc: boolean;
        // order by column
        public insightsOrderByCol: string;
        // order by direction
        public insightsOrderByColAsc: boolean;
        // order by column
        public portfolioOrderByCol: string;
        // order by direction 
        public portfolioOrderByColAsc: boolean; 
        public hasPortfolioPermision: boolean;

        public hasNotification: boolean;
        public notificationBody: string;

        constructor(
            private $rootScope: ng.IScope,
            private $scope: ng.IScope,
            private $q: ng.IQService,
            private $location: ng.ILocationService,
            private HomeService: HomeService,
            private notificationFactory: Common.INotificationFactory,
            private MostActiveReportService: MostActiveReports.MostActiveReportService,
            private MostRecentActivityService: MostRecentActivity.MostRecentActivityService,
            private PortfolioService: Portfolio.PortfolioService,
            private $modal: Common.IModal
            ) {

            var ctx = this;
            if (!ctx.$rootScope['userInfo']) {
                ctx.$rootScope['userInfo'] = angular.fromJson(localStorage.getItem('sust_userInfo'));
            }
            if (ctx.$rootScope['userInfo']) {
                ctx.accountId = ctx.$rootScope['userInfo'].accountId;
                ctx.userId = ctx.$rootScope['userInfo'].userId;
            }

            $scope['home'] = ctx;

            if (ctx.accountId && ctx.userId) { //only for logged in users

                ctx.eventsTopList = new Array();

                //ctx.hasPortfolioPermision = false;
                ctx.hasPortfolioPermision = ctx.PortfolioService.hasPermision();
                //NEWS
                ctx.getNewsTop();

                //EVENTS
                ctx.getEventsTop();

                //INSIGHTS
                ctx.insightsOrderByCol = 'DatePublished';
                ctx.insightsOrderByColAsc = false;
                ctx.getInsightsTop();

                //PORTFOLIOS
                ctx.getPortfoliosTop();

                //MOST ACTIVE REPORTS
                ctx.getMostActiveReportsTop();

                //MOST RECENT ACTIVITY
                ctx.getMostRecentActivityTop();

                //NOTIFICATION
                ctx.getNotification();
            }

            if (ctx.userId !== '') {
                ga('create', 'UA-4379897-6', {
                    'userId': ctx.userId,
                    'cookieDomain': 'none',
                    'name': 'globalAccess'
                });

                ga('globalAccess.set', 'dimension1', ctx.userId);

                var dateNow = new Date();
                var dateNowString = [dateNow.getDate(), dateNow.getMonth() + 1, dateNow.getFullYear()].join("/");
                var gaObject: any = {
                    Date: dateNowString,
                    AccountId: ctx.accountId,
                    UserId: ctx.userId
                };

                ga('globalAccess.send', {
                    'hitType': 'event',
                    'eventCategory': 'Home',
                    'eventAction': 'Dashboard',
                    'eventLabel': JSON.stringify(gaObject)
                });
            }
        }


        public tutorialPreview() {
            var ctx = this;

                 var $modalInstance = ctx.$modal.open(
                    {
                         templateUrl: '../../../Views/tutorial_dialog.tpl.html',
                        controller: 'TutorialController',
                        size: 'lg',
                        backdrop: 'static',
                        resolve: {
                            title: function () {
                                return "Global Access Overview";
                            },
                            url:function() {
                                return "http://www.sustainalytics.com/sites/default/files/uploads/2015-08-04-GAV1-GlobalAccessOverview.mp4";
                            }

                        }
                       
                    });

            
        }

        public tutorialPreview3() {
            var ctx = this;

            var $modalInstance = ctx.$modal.open(
                {
                    templateUrl: '../../../Views/tutorial_dialog.tpl.html',
                    controller: 'TutorialController',
                    size: 'lg',
                    backdrop: 'static',
                    resolve: {
                        title: function () {
                            return "Global Access Detailed Overview";
                        },
                        url: function () {
                            return "http://www.sustainalytics.com/sites/default/files/uploads/Global-Access-Introduction-Online-Demonstration-2015-09-10.mp4";
                        }

                    }

                });


        }

         
    
        //NEWS
        public getNewsTop(): ng.IPromise<{}> {
            var ctx = this;

            ctx.$rootScope['loading'] = true;

            var skip = 0;
            var take = 5;
            ctx.newsOrderByCol = 'DateCreated';
            ctx.newsOrderByColAsc = false;

            var promiseGet: ng.IPromise<NewsDashboardDto[]> = ctx.HomeService.getNewsTop(skip, take, [ctx.newsOrderByCol], ctx.newsOrderByColAsc, ctx.accountId);

            //on success
            promiseGet
                .then(function (lst) {
                    ctx.newsTopList = lst;
                })
                ['finally'](function () {
                    ctx.$rootScope['loading'] = false;
                });
            return promiseGet;
        }

        //EVENTS
        public getEventsTop(): ng.IPromise<{}> {
            var ctx = this;

            ctx.$rootScope['loading'] = true;

            var skip = 0;
            var take = 5;
            ctx.eventOrderByCol = 'StartDate';
            ctx.eventOrderByColAsc = false;

            var promiseGet: ng.IPromise<EventDashboardDto[]> = ctx.HomeService.getEventsTop(skip, take, [ctx.eventOrderByCol], ctx.eventOrderByColAsc);

            //on success
            promiseGet
                .then(function (lst) {
                    ctx.eventsTopList = lst;
                })
                ['finally'](function () {
                    ctx.$rootScope['loading'] = false;
                });
            return promiseGet;
        }


        //INSIGHTS
        public getInsightsTop(): ng.IPromise<{}> {
            var ctx = this;

            ctx.$rootScope['loading'] = true;

            var skip = 0;
            var take = 5;
            ctx.newsOrderByCol = 'DatePublished';
            ctx.newsOrderByColAsc = false;

            var promiseGet: ng.IPromise<InsightDashboardDto[]> = ctx.HomeService.getInsightsTop(skip, take, [ctx.insightsOrderByCol], ctx.insightsOrderByColAsc);

            //on success
            promiseGet
                .then(function (lst) {
                    ctx.insightsTopList = lst;
                })
                ['finally'](function () {
                    ctx.$rootScope['loading'] = false;
                });
            return promiseGet;
        }

        //PORTFOLIOS
        public getPortfoliosTop(): ng.IPromise<{}> {
            var ctx = this;

            ctx.$rootScope['loading'] = true;

            var skip = 0;
            var take = 5;
            ctx.portfolioOrderByCol = 'DateCreated';
            ctx.portfolioOrderByColAsc = false;

            var promiseGet: ng.IPromise<PortfolioDashboardListDto[]> = ctx.HomeService.getPortfoliosTop(skip, take, [ctx.portfolioOrderByCol], ctx.portfolioOrderByColAsc, ctx.accountId, ctx.userId);

            //on success
            promiseGet
                .then(function (lst) {
                    ctx.portfoliosTopList = lst["portfolios"];
                })
                ['finally'](function () {
                    ctx.$rootScope['loading'] = false;
                });
            return promiseGet;
        }

        // MOST ACTIVE REPORTS
        public getMostActiveReportsTop(): ng.IPromise<{}> {
            var ctx = this;

            ctx.$rootScope['loading'] = true;

            var skip = 0;
            var take = 5;

            var promiseGet: ng.IPromise<MostActiveReports.MostActiveReportDto[]> = ctx.MostActiveReportService.getList(skip, take);

            promiseGet.then(function (list) {
                ctx.mostActiveReportsTopList = list;
            })
            ['finally'](function () {
                    ctx.$rootScope['loading'] = false;
                });

            return promiseGet;
        }

        // MOST RECENT ACTIVITY
        public getMostRecentActivityTop(): ng.IPromise<MostRecentActivity.MostRecentActivityDto[]> {
            var ctx = this;

            ctx.$rootScope['loading'] = true;

            var skip = 0;
            var take = 5;

            var promiseGet: ng.IPromise<MostRecentActivity.MostRecentActivityDto[]> = ctx.MostRecentActivityService.getList(skip, take);

            promiseGet.then(function (list) {
                ctx.mostRecentActivityTopList = list;
            })
            ['finally'](function () {
                    ctx.$rootScope['loading'] = false;
                });

            return promiseGet;
        }

        public getNotification(): ng.IPromise<NotificationDto> {
            var ctx = this;

            var def = ctx.$q.defer();

            ctx.$rootScope['loading'] = true;

            var promiseGet: ng.IPromise<NotificationDto> = ctx.HomeService.getNotification();

            promiseGet.then(
                // success
                (response: NotificationDto) => {
                    //console.log("Debug: notification loaded");
                    //console.log(response);

                    if (response.status === 1) {
                        ctx.hasNotification = true;
                        ctx.notificationBody = response.body;
                    } else {
                        ctx.hasNotification = false;
                    }
                },
                // error
                () => {
                    def.reject();
                })
            ['finally'](() => {
                this.$rootScope['loading'] = false;
            });

            return promiseGet;
        }

        private redirectToCompanyPage(companyName: string) {
            var ctx = this;

            ctx.$location.path('/research/overview/' + companyName);
        }
    }

        // register controller 
        var home = angular.module('Sustainalytics.Home')
            .controller('HomeController',
            ['$rootScope', '$scope', '$q', '$location', 'HomeService', 'notificationFactory', 'MostActiveReportService', 'MostRecentActivityService', 'PortfolioService', '$modal', HomeController]);    

} 